package com.example.fiction.ui.fragment.books;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.example.fiction.BR;
import com.example.fiction.R;
import com.example.fiction.base.BaseRecyclerViewAdapter;
import com.example.fiction.base.BaseResult;
import com.example.fiction.db.BooksDBHelper;
import com.example.fiction.interfacz.IDirectory;
import com.example.fiction.response.BooksResponse;
import com.example.fiction.service.BooksLoader;
import com.example.fiction.ui.activity.reader.ReaderActivity;
import com.example.fiction.utils.IMEIUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;

/**
 * auth: 姚鸿杰
 * time: 2019/3/19 22:09
 **/
public class BooksViewModel extends BaseViewModel {

    private static final String TAG = "BooksViewModel";

    public ObservableField<String> title = new ObservableField<>("今天已读：0分钟");
    private RecyclerView booksRecycler;
    private Context context;
    private int booksLayout;    // 0：网格布局、1：线性布局

    private List<BooksItemViewModel> books = new ArrayList<>();
    private BaseRecyclerViewAdapter<BooksItemViewModel> booksAdapter;
    private BaseResult.IResponseListener<BooksResponse[]> listener = new BaseResult.IResponseListener<BooksResponse[]>() {

        @Override
        public void onSuccess(BooksResponse[] result) {
            for (BooksResponse item : result) {
                BooksItemViewModel book = new BooksItemViewModel(item.getBookId(),
                        item.getBookName(), item.getAuthor(), item.getProgress());
                books.add(book);
                BooksDBHelper dbHelper = new BooksDBHelper(item.getBookId(), item.getBookName(),
                        item.getAuthor(), item.getCover(), item.getChapter(),
                        item.getCharIndex(), item.getProgress(), item.getChapterList());
                dbHelper.save();
            }
            booksAdapter.setLists(books);
        }

        @Override
        public void onFail(String errorMsg) {
            Log.e(TAG, errorMsg);
        }
    };

    public BooksViewModel(@NonNull Application application) {
        super(application);
        context = application;
    }

    public void addRV(RecyclerView booksRecycler, final Activity activity) {
        this.booksRecycler = booksRecycler;
        initRecyclerView(activity);

    }

    /**
     * 获取书架信息，从数据库中获取
     */
    public void getBooksInfo() {
        List<BooksDBHelper> booksList = LitePal.findAll(BooksDBHelper.class);
        if (booksList.size() == 0) {    //判断数据库中是否有数据
            //无数据从服务器获取
            BaseResult<BooksResponse> result = new BaseResult<>(context);
            result.setRequestListListener(listener, BooksResponse[].class);
            Log.e(TAG, "getBooksInfo: 执行网络请求");
            try {
                //todo 暂时做IMEI处理待完成登录功能添加用户
                String data = IMEIUtils.getIMEI(context);
                if(TextUtils.isEmpty(data)) data = " ";
                BooksLoader loader = new BooksLoader(data, "getBooks");
                loader.getBooks().subscribe(result);
            } catch (Exception e) {
                //todo 代做异常处理
                e.printStackTrace();
            }
        } else {
            for (BooksDBHelper item : booksList) {
                BooksItemViewModel book = new BooksItemViewModel(item.getBookId(),
                        item.getBookName(), item.getAuthor(), item.getProgress());
                books.add(book);
            }
            booksAdapter.setLists(books);
        }
    }

    private void initRecyclerView(Activity activity) {
        SharedPreferences sf = context
                .getSharedPreferences("booksLayout", Context.MODE_PRIVATE);
        String layout;
        if (sf == null) {
            SharedPreferences.Editor editor = context
                    .getSharedPreferences("booksLayout", Context.MODE_PRIVATE).edit();
            editor.putString("layout", "grid");
            editor.apply();
            layout = "grid";
        } else layout = sf.getString("layout", "");

        booksLayout = TextUtils.equals(layout, "grid") ? 0 : 1;
        changeLayout(activity, true);
    }

    public void changeLayout(final Activity activity, boolean isInit) {
        if (booksRecycler == null) return;
        if (!isInit) booksLayout = booksLayout == 0 ? 1 : 0;
        if (booksLayout == 0) { //是否为线性布局
            booksAdapter = new BaseRecyclerViewAdapter<>(context, activity.getLayoutInflater(),
                    R.layout.item_books_grid, BR.booksViewModel, books);
            booksRecycler.setLayoutManager(new GridLayoutManager(activity, 3));
        } else {
            booksAdapter = new BaseRecyclerViewAdapter<>(activity, activity.getLayoutInflater(),
                    R.layout.item_books_line, BR.booksViewModel, books);
            booksRecycler.setLayoutManager(new LinearLayoutManager(activity));
        }
        SharedPreferences.Editor editor = context
                .getSharedPreferences("booksLayout", Context.MODE_PRIVATE).edit();
        editor.putString("layout", booksLayout == 1 ? "line" : "grid");
        editor.apply();
        booksAdapter.setItemClickListener(new IDirectory<BooksItemViewModel>() {
            @Override
            public void itemClick(View v, int position, BooksItemViewModel booksItemViewModel) {
                Intent intent = new Intent(context, ReaderActivity.class);
                intent.putExtra("bookId", booksItemViewModel.bookId);
                activity.startActivity(intent);
            }
        });
        booksRecycler.setAdapter(booksAdapter);
    }

}
